# app/api/v1/endpoints/auth.py

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from app.api.v1 import deps
from app.schemas.user import User, UserCreate
from app.schemas.token import Token
from app.services import user_service
from app.core import security

router = APIRouter()


@router.post("/register", response_model=User, status_code=status.HTTP_201_CREATED)
def register_user(
        user_in: UserCreate,
        db: Session = Depends(deps.get_db)
):
    """
    用户注册接口。
    """
    user = user_service.register_new_user(db=db, user_in=user_in)
    return user


@router.post("/login", response_model=Token)
def login_for_access_token(
        db: Session = Depends(deps.get_db),
        form_data: OAuth2PasswordRequestForm = Depends()
):
    """
    用户登录获取 access token。
    FastAPI 的 OAuth2PasswordRequestForm 会要求客户端以 form-data 的形式
    发送 'username' 和 'password'。
    """
    user = user_service.authenticate_user(
        db, email=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    access_token = security.create_access_token(
        subject=user.email,
    )
    return {"access_token": access_token, "token_type": "bearer"}